<?php

namespace App\Http\Controllers\Auth;

use App\Models\SMSConfirmationCode;
use App\Http\Controllers\Controller;
use App\Services\UserService;
use Dotenv\Exception\ValidationException;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
use Illuminate\Foundation\Auth\RegistersUsers;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;
    protected $userService;
    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct(UserService $userService)
    {
        $this->middleware('guest');
        $this->userService = $userService;
    }

    /**
     * @param array $data
     * @return mixed
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'mobile' => 'required|string|max:255|unique:users',
            'confirmation-code' => 'required|string|max:255',
            'password' => 'required|string|min:6|confirmed'
        ]);
    }
    /**
     * Handle a registration request for the application.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function register(Request $request)
    {
        try {
//            dd($request->all());
            $this->validator($request->all())->validate();
            $user = $this->create($request->all());
            $this->guard()->login($user);

            return $this->registered($request, $user)
                ?: redirect($this->redirectPath());
        } catch (ValidationException $e) {
            throw $e;
        } catch (\Exception $e) {
            return redirect('register')
                ->withErrors(['mobile' => $e->getMessage()])
                ->withInput();
        }
    }

    /**
     *
     * Create a new user instance after a valid registration.
     *
     * @param array $data
     * @return $this|\Illuminate\Database\Eloquent\Model
     * @throws \Exception
     */
    protected function create(array $data)
    {

        $mobile = $data['mobile'];
        $code = SMSConfirmationCode::query()->where(["mobile" => $mobile])->orderBy('expired', 'desc')->first();
        if (!$code || !$code->checkSMSConfirmationCode($data['confirmation-code'], $code->code, $code->expired)) {
            throw new \Exception('验证码不正确');
        }
        $user = $this->userService->registerUser($data);
        return $user;
    }
}
